package com.xfcy.blog.strategy.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xfcy.blog.common.constant.Constant;
import com.xfcy.blog.common.enums.PublishEnum;
import com.xfcy.blog.entity.Article;
import com.xfcy.blog.mapper.ArticleMapper;
import com.xfcy.blog.strategy.SearchStrategy;
import com.xfcy.blog.vo.ArticleSearchVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 晓风残月Lx
 * @date 2023/4/12 15:32
 */
@Service("mysqlStrategyImpl")
public class MysqlSearchStrategyImpl implements SearchStrategy {

    @Resource
    private ArticleMapper articleMapper;

    /**
     * 搜索功能搜索文章和标题
     * @param keywords
     * @return
     */
    @Override
    public List<ArticleSearchVO> searchArticle(String keywords) {
        // 搜索文章 (简介和标题模糊查询)
        List<Article> articles = articleMapper.selectList(new LambdaQueryWrapper<Article>()
                .eq(Article::getIsPublish, PublishEnum.PUBLISH.getCode())
                .and(i -> i.like(Article::getTitle, keywords)
                        .or()
                        .like(Article::getSummary, keywords))
                .orderByDesc(Article::getIsStick, Article::getCreateTime));

        // 高亮处理
        List<ArticleSearchVO> articleSearchVOList = articles.stream().map(item -> {
            // 获取关键词第一次出现的位置
            String articleSummary = item.getSummary();
            int index = item.getSummary().indexOf(keywords);
            if (index != -1) {
                // 文章简介高亮
                articleSummary = articleSummary.replaceAll(keywords, Constant.START_TAG + keywords + Constant.LAST_TAG);
            }
            // 文章标题高亮
            String articleTitle = item.getTitle().replaceAll(keywords, Constant.START_TAG + keywords + Constant.LAST_TAG);
            return new ArticleSearchVO(item.getId(), articleTitle, articleSummary);
        }).collect(Collectors.toList());

        return articleSearchVOList;
    }
}
